package com.srkj.activiti.service.impl;

import com.srkj.activiti.entity.Act_product_record;
import com.srkj.activiti.service.ProcessService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * zhangshaoxiong
 * com.srkj.activiti.service.impl
 * 2018/6/2 22:40
 */
@Service
public class ProcessServiceImpl implements ProcessService {
    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private RuntimeService runtimeService;
    @Override
    public InputStream getDiagramByProDefinitionId_noTrace(String resourceType,String processDefinitionId) throws Exception {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(processDefinitionId)
                .singleResult();
        String resourceName = null;
        if (resourceType.equals("png") || resourceType.equals("image")){
            resourceName = processDefinition.getDiagramResourceName();
        }else if (resourceType.equals("xml")){
            resourceName = processDefinition.getResourceName();
        }
        //获取流程图，根据部署id 和name
        InputStream resourceAsStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), resourceName);
        return resourceAsStream;
    }



    @Override
    public String startProductProcess(Act_product_record apr) throws Exception{
        //用来设置启动流程的人员ID，引擎会自动吧用户ID保存到activiti:initiator中
        identityService.setAuthenticatedUserId(apr.getUserid().toString());
        Map<String,Object> variables = new HashMap<>();
        variables.put("product",apr);
        variables.put("businessKey",apr.getId());
        //启动流程
        String businessKey = apr.getId();
        ProcessInstance processInstance = runtimeService.startProcessInstanceById("productProcess",businessKey,variables);
        return processInstance.getId();
    }


}
